package com.enation.app.javashop.consumer.shop.promotion;

import com.enation.app.javashop.consumer.core.event.*;
import com.enation.app.javashop.core.base.message.GoodsChangeMsg;
import com.enation.app.javashop.core.base.message.GoodsSkuChangeMsg;
import com.enation.app.javashop.core.base.message.OrderStatusChangeMsg;
import com.enation.app.javashop.core.base.message.ShetuanChangeMsg;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.client.trade.ShetuanClient;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanGoodsStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsOperateManager;
import com.enation.app.javashop.core.promotion.tool.model.dto.PromotionDetailDTO;
import com.enation.app.javashop.core.promotion.tool.model.dto.PromotionGoodsDTO;
import com.enation.app.javashop.core.promotion.tool.model.enums.PromotionTypeEnum;
import com.enation.app.javashop.core.promotion.tool.service.PromotionGoodsManager;
import com.enation.app.javashop.core.promotion.tool.support.PromotionCacheKeys;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.model.enums.OrderTypeEnum;
import com.enation.app.javashop.core.trade.order.model.enums.ServiceStatusEnum;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 社区团购消费者
 */
@Component
public class ShetuanConsumer  implements ShetuanChangeEvent, GoodsChangeEvent, GoodsPriorityChangeEvent , GoodsSkuChangeEvent {
    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private ShetuanClient shetuanClient;

    @Autowired
    private ShetuanGoodsManager shetuanGoodsManager;

    @Autowired
    private ShetuanGoodsOperateManager shetuanGoodsOperateManager;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private PromotionGoodsManager promotionGoodsManager;


    /**
     * 社团活动 状态修改（实时增量更新， 定时全量更新）
     *
     * @param shetuanChangeMsg
     */
    @Override
    public void shetuanChange(ShetuanChangeMsg shetuanChangeMsg) {
        // 更新社团商品索引
        ShetuanDO shetuan= shetuanClient.queryShetuanById(shetuanChangeMsg.getShetuanId());
        List<ShetuanGoodsDO> goodsDOS = shetuanClient.querySheuanGoods(shetuanChangeMsg.getShetuanId(),shetuanChangeMsg.getSkuIds());
        List<PromotionGoodsDTO> promotionGoodsDTOS = new ArrayList<>();
        List<Integer> deleteSkuIds = new ArrayList<>();

        List<Integer> goodsIds = goodsDOS.stream().map(ShetuanGoodsDO::getGoodsId).distinct().collect(Collectors.toList());
        // 查询商品基础信息
        Map<Integer, Map<String, Object>> goodsIndex = getGoods(goodsIds.toArray(new Integer [goodsIds.size()]));
        // 查询商品基础信息
        for (ShetuanGoodsDO shetuanGoodsDO : goodsDOS) {
            // 新增索引（新增或者更新）
            ShetuanGoodsVO shetuanGoodsVO = getShetuanGoodsVO(shetuan, shetuanGoodsDO);

            if(shetuanGoodsVO.getStatus().equals(ShetuanGoodsStatusEnum.ON_LINE.getIndex())
                    && shetuanGoodsVO.getShetuanStatus().equals(ShetuanStatusEnum.ON_LINE.getIndex()) ){
                //添加索引
                shetuanClient.addIndex(shetuanGoodsVO,goodsIndex.get(shetuanGoodsVO.getGoodsId()));

                // 新增促销商品
                PromotionGoodsDTO goodsDTO=new PromotionGoodsDTO();
                goodsDTO.setNum(shetuanGoodsDO.getLimitNum());
                goodsDTO.setPrice(shetuanGoodsDO.getShetuanPrice());
                goodsDTO.setSellerId(shetuanGoodsDO.getSellerId());
                goodsDTO.setQuantity(shetuanGoodsDO.getGoodsNum());
                goodsDTO.setProductId(shetuanGoodsDO.getSkuId());
                goodsDTO.setGoodsId(shetuanGoodsDO.getGoodsId());
                goodsDTO.setGoodsName(shetuanGoodsDO.getGoodsName());
                goodsDTO.setSn(shetuanGoodsDO.getSn());

                promotionGoodsDTOS.add(goodsDTO);
            }else{
                // 删除索引
                shetuanClient.delIndex(shetuanGoodsDO.getShetuanId(),shetuanGoodsVO.getSkuId());
                // 删除促销商品
                deleteSkuIds.add(shetuanGoodsDO.getSkuId());
            }
        }

        PromotionDetailDTO detailDTO = new PromotionDetailDTO();
        detailDTO.setStartTime(shetuan.getStartTime());
        detailDTO.setEndTime(shetuan.getEndTime());
        detailDTO.setActivityId(shetuan.getShetuanId());
        detailDTO.setTitle(shetuan.getShetuanName());
        detailDTO.setPromotionType(PromotionTypeEnum.SHETUAN.name());

        //将活动商品入库--->>>>es_promotion_goods
        if(!CollectionUtils.isEmpty(deleteSkuIds)){
            this.promotionGoodsManager.deleteByActivityId(shetuan.getShetuanId(),deleteSkuIds);
            logger.info("删除社团商品促销信息");
            logger.info(deleteSkuIds.toString());
        }
        if(!CollectionUtils.isEmpty(promotionGoodsDTOS)){
            this.promotionGoodsManager.add(promotionGoodsDTOS,detailDTO);
            logger.info("添加社团商品促销信息");
            logger.info(promotionGoodsDTOS.toString());
        }
    }

    private ShetuanGoodsVO getShetuanGoodsVO(ShetuanDO shetuan, ShetuanGoodsDO shetuanGoodsDO) {
        ShetuanGoodsVO shetuanGoodsVO = new ShetuanGoodsVO();
        BeanUtil.copyProperties(shetuanGoodsDO,shetuanGoodsVO);
        shetuanGoodsVO.setStartTime(shetuan.getStartTime());
        shetuanGoodsVO.setEndTime(shetuan.getEndTime());
        shetuanGoodsVO.setPickTime(shetuan.getPickTime());
        shetuanGoodsVO.setShetuanStatus(shetuan.getStatus());
        shetuanGoodsVO.setShetuanId(shetuan.getShetuanId());
        return shetuanGoodsVO;
    }


    /**
     * 普通商品修改出发社团团购商品索引修改
     */
    @Override
    public void goodsChange(GoodsChangeMsg goodsChangeMsg) {

        updateIndex(goodsChangeMsg);

    }

    private Map<Integer, Map<String, Object>> getGoods(Integer[] goodsIds) {
        List<Map<String, Object>> goodsList = goodsClient.getGoodsAndParams(goodsIds);
        Map<Integer, Map<String, Object>> goodsIndex = Maps.newHashMap();
        for (Map<String, Object> goods : goodsList) {
            goodsIndex.put((Integer) goods.get("goods_Id"),goods);
        }
        return goodsIndex;
    }

    @Override
    public void priorityChange(GoodsChangeMsg goodsChangeMsg) {
        updateIndex(goodsChangeMsg);
    }

    private void updateIndex(GoodsChangeMsg goodsChangeMsg) {
        Integer[] goodsIds = goodsChangeMsg.getGoodsIds();
        // 查询社区团购商品
        List<ShetuanGoodsDO> shetuanGoodsList = shetuanClient.querySheuanGoodsByGoodsIds(goodsIds);
        // 查询商品基础信息
        Map<Integer, Map<String, Object>> goodsIndex = getGoods(goodsIds);
        // 更新索引
        for (ShetuanGoodsDO shetuanGoodsDO : shetuanGoodsList) {
            ShetuanDO shetuanDO = shetuanClient.queryShetuanById(shetuanGoodsDO.getShetuanId());

            if (shetuanGoodsDO.getStatus().equals(ShetuanGoodsStatusEnum.ON_LINE.getIndex()) && shetuanDO.getStatus().equals(ShetuanStatusEnum.ON_LINE.getIndex())) {
                ShetuanGoodsVO shetuanGoodsVO = getShetuanGoodsVO(shetuanDO, shetuanGoodsDO);

                Map<String, Object> goods = goodsIndex.get(shetuanGoodsDO.getGoodsId());

                //添加索引
                shetuanClient.addIndex(shetuanGoodsVO, goods);
            }
        }
    }

    /**
     * sku删除之后 需要删除下架社区团购商品,不得重新进行上架操作
     * @param goodsSkuChangeMsg
     */
    @Override
    public void goodsSkuChange(GoodsSkuChangeMsg goodsSkuChangeMsg) {
        List<Integer> skuIds = goodsSkuChangeMsg.getSkuIds();
        if(goodsSkuChangeMsg.getOperationType().equals(GoodsSkuChangeMsg.DELETE_OPERATION) && !CollectionUtils.isEmpty(skuIds)){
           List<ShetuanGoodsDO> shetuanGoodsDOS= shetuanGoodsManager.getBySkuIds(skuIds,ShetuanGoodsStatusEnum.ON_LINE.getIndex());
            for (ShetuanGoodsDO shetuanGoodsDO : shetuanGoodsDOS) {
                shetuanGoodsOperateManager.operateStGoodsStatus(shetuanGoodsDO.getId(),ShetuanGoodsStatusEnum.OFF_LINE.getIndex());
            }
        }
    }
}
